<template>
  <div id="main">
    <h2>购买课程记录管理</h2>
    <div class="head">
      <el-input
        v-model="searchTableInfo"
        placeholder="请输入搜索内容"
        style="width:240px;float: right;margin:20px;"
      />
    </div>
    <div id="table-area">
      <el-table
        v-loading="listLoading"
        :data="list.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column label="序号" type="index" align="center">
          <template scope="scope">
            <span>{{ (currentPage - 1) * pagesize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="studentName"
          label="学生姓名"
          width="150px"
        />

        <el-table-column
          align="center"
          prop="classStatus"
          label="课程状态"
          width="150px"
        />

        <el-table-column
          align="center"
          prop="payId"
          label="课程订单id"
          width="300px"
        />

        <el-table-column
          align="center"
          prop="purchaseTimes"
          label="购买课程次数"
        />
        <el-table-column
          align="center"
          prop="classTimes"
          label="已使用课程次数"
        />
        <el-table-column
          align="center"
          prop="remainingTimes"
          label="剩余课程次数"
        />

        <el-table-column align="center" label="操作">
          <template slot-scope="Scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="handleOpen('修改课程购买记录', 2, Scope.row.purchaseId)"
            >编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div id="pages">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5, 10]"
          :page-size="pagesize"
          layout="total, sizes,prev, pager, next"
          :total="list.length"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog
      title=""
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
    >
      <el-form
        ref="Records"
        :model="Records"
        label-position="top"
        :rules="rules"
      >
        <el-form-item
          prop="studentId"
          label="学生姓名"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="Records.studentId"
            filterable
            placeholder="请选择"
            style="width: 40%;"
          >
            <el-option
              v-for="item in child"
              :key="item.studentId"
              :label="item.String"
              :value="item.studentId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="classStatus"
          label="班级状态"
          :label-width="formLabelWidth"
        >
          <el-select v-model="Records.classStatus" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="payId"
          label="课程订单id"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="Records.payId"
            autocomplete="off"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item
          prop="purchaseTimes"
          label="购买课程次数"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="Records.purchaseTimes"
            autocomplete="off"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item
          prop="classTimes"
          label="已使用课程次数"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="Records.classTimes"
            autocomplete="off"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item
          prop="remainingTimes"
          label="剩余课程次数"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="Records.remainingTimes"
            autocomplete="off"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="editType == 2"
          type="primary"
          @click="handleUpdate('Records')"
        >修 改</el-button>
        <!-- <el-button
          v-if="editType == 1"
          type="primary"
          @click="handleAddUser('Records')"
          >添 加</el-button
        > -->
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  updateRecordsById,
  getRecordsbyId,
  getAllRecords,
  getStudentString
} from '@/api/purchaseCourseRecords'

export default {
  data() {
    return {
      options: [
        {
          value: 1,
          label: '已完成'
        },
        {
          value: 0,
          label: '未完成'
        }
      ],
      newRecord: {
        purchaseId: '',
        studentName: '',
        classStatus: '',
        payId: '',
        purchaseTimes: '',
        classTimes: '',
        remainingTimes: ''
      },
      search: '',
      currentPage: 1, // 默认显示页面为1
      pagesize: 5, //    每页的数据条数
      // list: [],
      tableList: [],
      searchTableInfo: '',
      Records: [],
      listLoading: false,
      dialogFormVisible: false,
      editType: 1, // 1 添加 2 修改
      child: {},
      formLabelWidth: '200px',
      rules: {
        attendance: [
          { required: true, message: '出勤情况不能为空', trigger: 'blur' }
        ],
        postTime: [{ required: true, message: '打卡时间', trigger: 'blur' }],
        reasonAbsence: [
          { required: true, message: '出勤原因', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 根据计算属性模糊搜索
    list() {
      const searchTableInfo = this.searchTableInfo
      console.log(this.searchTableInfo)
      if (searchTableInfo) {
        // filter() 方法创建一个新的数组，新数组中的元素是通过检查指定数组中符合条件的所有元素。
        // 注意： filter() 不会对空数组进行检测。
        // 注意： filter() 不会改变原始数组。
        return this.tableList.filter(data => {
          console.log('success' + data)
          // some() 方法用于检测数组中的元素是否满足指定条件;
          // some() 方法会依次执行数组的每个元素：
          // 如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测;
          // 如果没有满足条件的元素，则返回false。
          // 注意： some() 不会对空数组进行检测。
          // 注意： some() 不会改变原始数组。
          return Object.keys(data).some(key => {
            // indexOf() 返回某个指定的字符在某个字符串中首次出现的位置，如果没有找到就返回-1；
            // 该方法对大小写敏感！所以之前需要toLowerCase()方法将所有查询到内容变为小写。
            return (
              String(data[key])
                .toLowerCase()
                .indexOf(searchTableInfo) > -1
            )
          })
        })
      }
      return this.tableList
    }
  },

  created() {
    this.fetchData()
    this.getAllChild()
  },
  methods: {
    // 每页下拉显示数据
    handleSizeChange: function(size) {
      this.pagesize = size
    },
    // 点击第几页
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
    },
    handleClick(row) {
      console.log(row)
    },
    fetchData() {
      this.tableList = []
      this.listLoading = true
      getAllRecords().then(data => {
        this.newRecord
        for (var i = 0; i < data.obj.length; i++) {
          this.newRecord.purchaseId = data.obj[i].purchaseId
          this.newRecord.studentName = data.obj[i].student.studentName
          this.newRecord.payId = data.obj[i].payId
          this.newRecord.purchaseTimes = data.obj[i].purchaseTimes
          this.newRecord.classTimes = data.obj[i].classTimes
          this.newRecord.remainingTimes = data.obj[i].remainingTimes
          if (data.obj[i].classStatus === 0) {
            this.newRecord.classStatus = '未完成'
          }
          if (data.obj[i].classStatus === 1) {
            this.newRecord.classStatus = '已完成'
          }
          this.tableList.push(this.newRecord)
          this.newRecord = {}
        }
        console.log(this.tableList)
        this.listLoading = false
      })
    },
    getAllChild() {
      getStudentString().then(res => {
        this.child = res.obj
      })
    },

    handleOpen(title, type, id) {
      this.Records = {}
      this.dialogFormVisible = true
      this.title = title
      this.editType = type
      if (type === 2) {
        getRecordsbyId(id).then(resp => {
          console.log(resp)
          this.Records = resp.obj
          console.log(this.Records)
        })
      }
    },
    handleClose() {
      this.dialogFormVisible = false
      this.Records = {}
    },
    handleUpdate(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.Records)
          updateRecordsById(this.Records).then(resp => {
            this.$notify({
              title: '修改成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    }
    // getAllJurisdiction() {
    //   getAllJurisdiction().then((resp) => {
    //     this.jurisdiction = resp.obj
    //   })
    // },
  }
}
</script>

<style scoped>
#main {
  margin-left: 5px;
  margin-right: 5px;
}

#table-area {
  margin-top: 80px;
  margin-left: 10px;
  margin-right: 10px;
}
</style>
